import {
  changeUserStatus,
  delUser,
  deptTreeSelect,
  getUser,
  listUser,
  resetUserPwd,
} from '@/api/system/user'
import { addDateRange, formatDate } from '@/utils/common'
import { useDicts } from '@/utils/dict'
import { downloadFile } from '@/utils/http'
import { message } from '@/utils/message'
import type { PaginationProps } from '@pureadmin/table'
import { useGlobal } from '@pureadmin/utils'
import { type DateModelType, ElMessageBox, type FormInstance } from 'element-plus'
import { onMounted, reactive, ref, toRefs } from 'vue'
import { useRouter } from 'vue-router'

export function useUser() {
  const data = reactive({
    form: {
      userId: undefined,
      deptId: undefined,
      userName: undefined,
      nickName: undefined,
      password: undefined,
      phonenumber: undefined,
      email: undefined,
      sex: undefined,
      status: '0',
      remark: undefined,
      postIds: [],
      roleIds: [],
    },
    queryParams: {
      userName: undefined,
      phonenumber: undefined,
      status: undefined,
      deptId: undefined,
    },
  })
  const { $config } = useGlobal<GlobalPropertiesApi>()
  const osTypes = [0, $config.OSType]
  const { form, queryParams } = toRefs(data)
  const { sys_normal_disable } = useDicts('sys_normal_disable')
  const deptTreeRef: any = ref<FormInstance>()
  const formDialogVisible = ref(false)
  const uploadDialogVisibie = ref(false)

  const router = useRouter()

  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const showSelection = true

  const userId = ref(0)
  const title = ref('')
  const dataList = ref([])
  const loading = ref(true)
  const dateRange = ref<DateModelType>(null)

  const deptName = ref('')
  const deptOptions = ref(undefined)
  const initPassword = ref(undefined)
  const postOptions = ref([])
  const roleOptions = ref([])

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
  })
  const columns: TableColumnList = [
    {
      type: 'selection',
      width: 55,
      align: 'left',
      hide: ({ checkList }) => !checkList.includes('勾选列'),
    },
    {
      label: '序号',
      type: 'index',
      width: 70,
      hide: ({ checkList }) => !checkList.includes('序号列'),
    },
    {
      label: '用户编号',
      prop: 'userId',
      minWidth: 100,
    },
    {
      label: '用户名称',
      prop: 'userName',
      minWidth: 100,
    },
    {
      label: '用户昵称',
      prop: 'nickName',
      minWidth: 100,
    },
    {
      label: '部门',
      prop: 'dept.deptName',
      minWidth: 100,
    },
    {
      label: '手机号码',
      prop: 'phonenumber',
      minWidth: 140,
    },
    {
      label: '状态',
      prop: 'status',
      minWidth: 100,
      cellRenderer: (scope) => {
        return (
          <el-switch
            v-model={scope.row.status}
            active-value={'0'}
            inactive-value={'1'}
            onChange={() => handleStatusChange(scope.row)}
          ></el-switch>
        )
      },
    },
    {
      label: '创建时间',
      minWidth: 180,
      prop: 'createTime',
      formatter: ({ createTime }) => formatDate(createTime),
    },
    {
      label: '操作',
      fixed: 'right',
      width: 180,
      slot: 'operation',
    },
  ]

  /** 通过条件过滤节点  */
  function filterNode(value, data) {
    if (!value) return true
    return data.label.indexOf(value) !== -1
  }

  /** 查询部门下拉树结构 */
  function getDeptTree() {
    deptTreeSelect().then((response: any) => {
      deptOptions.value = response.data
    })
  }

  /** 节点单击事件 */
  function handleNodeClick(data) {
    queryParams.value.deptId = data.id
    onSearch()
  }

  /** 查询列表 */
  async function onSearch() {
    loading.value = true
    const params = {
      ...queryParams.value,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
    }
    const { rows, total } = await listUser(addDateRange(params, dateRange.value))
    dataList.value = rows
    pagination.total = total
    loading.value = false
  }

  /** 重置新增的表单  */
  function reset() {
    form.value = {
      userId: undefined,
      deptId: undefined,
      userName: undefined,
      nickName: undefined,
      password: undefined,
      phonenumber: undefined,
      email: undefined,
      sex: undefined,
      status: '0',
      remark: undefined,
      postIds: [],
      roleIds: [],
    }
  }

  /** 新增按钮操作 */
  function handleAdd() {
    reset()
    getUser(osTypes).then((response: any) => {
      const { data } = response
      postOptions.value = data.posts
      roleOptions.value = data.roles
      formDialogVisible.value = true
      title.value = '添加用户'
      form.value.password = initPassword.value
    })
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset()
    const userId = row.userId || ids.value
    formDialogVisible.value = true
    getUser(osTypes, userId).then((response: any) => {
      const { data } = response
      form.value = data.user
      postOptions.value = data.posts
      roleOptions.value = data.roles
      form.value.postIds = data.postIds
      form.value.roleIds = data.roleIds
      form.value.password = ''
      formDialogVisible.value = true
      title.value = '修改用户'
    })
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const dictIds = row.userId || ids.value
    ElMessageBox.confirm('数据一经删除不可恢复，请再次确认！', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      await delUser(dictIds)
      message('删除成功', { type: 'success' })
      onSearch()
    })
  }

  /** 导入按钮操作 */
  function handleImport() {
    title.value = '导入用户'
    uploadDialogVisibie.value = true
  }

  /** 导出按钮操作 */
  function handleExport() {
    downloadFile(
      'system/user/export',
      {
        ...queryParams.value,
      },
      `用户管理.xlsx`
    )
  }

  /** 用户状态修改  */
  function handleStatusChange(row) {
    const text = row.status === '0' ? '启用' : '停用'
    ElMessageBox.confirm('确认要"' + text + '""' + row.userName + '"用户吗?')
      .then(function () {
        return changeUserStatus(row.userId, row.status)
      })
      .then(() => {
        message(text + '成功', { type: 'success' })
      })
      .catch(function () {
        row.status = row.status === '0' ? '1' : '0'
      })
  }

  /** 重置密码按钮操作 */
  function handleResetPwd(row) {
    ElMessageBox.prompt('请输入"' + row.userName + '"的新密码', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: '用户密码长度必须介于 5 和 20 之间',
    }).then(({ value }) => {
      resetUserPwd(row.userId, value).then(() => {
        message('修改成功，新密码是：' + value, { type: 'success' })
      })
    })
  }

  /** 跳转角色分配 */
  function handleAuthRole(userId: number) {
    router.push({ name: 'AuthRole', params: { userId } })
  }

  /** 改变多选项 */
  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.userId)
    single.value = selection.length != 1
    multiple.value = !selection.length
  }

  /** 改变分页大小 */
  function handleSizeChange(val: number) {
    pagination.pageSize = val
    onSearch()
  }

  /** 改变当前分页 */
  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    onSearch()
  }

  const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    dateRange.value = null
    onSearch()
  }

  onMounted(() => {
    onSearch()
    getDeptTree()
  })

  return {
    form,
    title,
    userId,
    loading,
    columns,
    deptName,
    dataList,
    multiple,
    dateRange,
    pagination,
    deptOptions,
    postOptions,
    roleOptions,
    queryParams,
    deptTreeRef,
    showSelection,
    formDialogVisible,
    sys_normal_disable,
    uploadDialogVisibie,
    onSearch,
    resetForm,
    handleAdd,
    filterNode,
    handleUpdate,
    handleDelete,
    handleExport,
    handleImport,
    handleResetPwd,
    handleAuthRole,
    handleNodeClick,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
  }
}
